package com.amado.course40Reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by Administrator on 2018/8/4.
 */
public class S02ReflectTest {
    public static void main(String[] args) {
        Goods goods = new Goods("商品",12);
        //只能取public修饰的属性、字段
        Goods.class.getFields();
        //返回 Field 对象的一个数组，包含了私有private的属性
        for(Field field:Goods.class.getDeclaredFields()){
            //设置private修饰的字段为可访问
            field.setAccessible(true);
            System.out.print("字段类型"+field.getType()+"名称" +field.getName());
            try {
                System.out.println("  值 "+field.get(goods));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        
        //返回 method 对象的一个数组，包含了私有private的方法
        for(Method method:Goods.class.getMethods()){
            //设置private修饰的方法为可访问
            method.setAccessible(true);
            System.out.print("字段返回值  "+method.getReturnType()+"  名称 " +method.getName()+"  参数个数  "+method.getParameterCount());
            Class[]  paramTypes = method.getParameterTypes();
            for(Class paramClass:paramTypes){
                System.out.print(paramClass+"  ");
            }
            System.out.println();
            try {
                if(method.getName().contains("get")) {
                    System.out.println("get "+ method.invoke(goods));
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        //获取构造方法
        Constructor[] constructorArray = Goods.class.getConstructors();
        try {
            //newInstance是构造goods对应 等同于 new Goods("商品2",11)
            Goods newGoods = (Goods)constructorArray[0].newInstance("商品2",11);
            System.out.println(newGoods.getPrice());
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
